/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package geracaopdf;

/**
 *
 * @author Igor
 */
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import controlador.ControladorProduto;
import controlador.ControladorTransacoes;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import utils.Cliente;
import utils.Compra;
import utils.Transacoes;

public class TransacoesNotaDeVendaPDF {

    private Compra compraEscolhida;
    PdfContentByte cb;
    private static String file;
    private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
            Font.BOLD);
    private static Font bigBold = new Font(Font.FontFamily.TIMES_ROMAN, 14,
            Font.BOLD);
    private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
            Font.NORMAL, BaseColor.RED);
    private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
            Font.BOLD);
    private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
            Font.BOLD);
    private static Font smallestBold = new Font(Font.FontFamily.TIMES_ROMAN, 6,
            Font.BOLD);
    private static Font capsNoBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
            Font.NORMAL);
    private static Font smallNormal = new Font(Font.FontFamily.TIMES_ROMAN, 10,
            Font.NORMAL);

    public TransacoesNotaDeVendaPDF(Compra compraEscolhida) {
        this.compraEscolhida = compraEscolhida;
        Document document = new Document();
        file = "C:/Arquivos PDF/Vendas/" + "Nota de Venda " + compraEscolhida.getId() + " - " + compraEscolhida.getNomeDoCliente() + ".pdf";
        try {
            try {
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                document.open();
                addMetaData(document);
                addTitlePage(document);
                document.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ClienteIndividualPDF.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (DocumentException ex) {
            Logger.getLogger(ClienteIndividualPDF.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void addMetaData(Document document) {
        document.addTitle("Nota de venda ");
        document.addSubject("Notas de venda");
        document.addKeywords("Java, PDF, Venda");
        document.addAuthor("Frente de Caixa");
        document.addCreator("Frente de Caixa");
    }

    private void addTitlePage(Document document)
            throws DocumentException {
        Paragraph preface = new Paragraph();
        try {
            Image barraNegra = Image.getInstance("C:/Arquivos PDF/Configurações/barraNegra.png");
            barraNegra.setAbsolutePosition(0, 830f);
            document.add(barraNegra);


        } catch (BadElementException ex) {
            Logger.getLogger(TransacoesNotaDeVendaPDF.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(TransacoesNotaDeVendaPDF.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TransacoesNotaDeVendaPDF.class.getName()).log(Level.SEVERE, null, ex);
        }
        document.add(preface);
        // We add one empty line
        addEmptyLine(preface, 1);
        // Lets write a big header
        Paragraph titulo = new Paragraph("Nota de Venda", catFont);
        titulo.setAlignment(Element.ALIGN_CENTER);
        preface.add(titulo);

        addEmptyLine(preface, 2);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph("ID da transação (protocolo)", bigBold));
        preface.add(new Paragraph(String.valueOf(compraEscolhida.getId()), capsNoBold));

        addEmptyLine(preface, 1);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph("Nome do comprador", bigBold));
        preface.add(new Paragraph(compraEscolhida.getNomeDoCliente().toUpperCase(), capsNoBold));

        addEmptyLine(preface, 1);
        // Will create: Report generated by: _name, _date
        preface.add(new Paragraph("CPF/CNPJ do comprador", bigBold));
        preface.add(new Paragraph(compraEscolhida.getCpf_cnpjDoCliente().toUpperCase(), capsNoBold));

        addEmptyLine(preface, 1);
        preface.add(new Paragraph("Data da transação (ano-mês-dia):", bigBold));
        preface.add(new Paragraph(compraEscolhida.getDataDaCompra().toString(), capsNoBold));

        addEmptyLine(preface, 2);
        createTable(preface);

        DecimalFormat df = new DecimalFormat("#.##");
        addEmptyLine(preface, 4);

        double descontoTotal = compraEscolhida.getDescontoTotal();
        Paragraph textoDesconto = new Paragraph("Desconto final da compra (R$):", capsNoBold);
        textoDesconto.setAlignment(Element.ALIGN_RIGHT);
        preface.add(textoDesconto);

        addEmptyLine(preface, 1);
        Paragraph descontoFinal = new Paragraph(df.format(descontoTotal).replace(".", ","), catFont);
        descontoFinal.setAlignment(Element.ALIGN_RIGHT);
        preface.add(descontoFinal);


        double valorTransferencia = (compraEscolhida.getPrecoTotal());
        Paragraph textoValor = new Paragraph("Valor final da compra (já com desconto) (R$):", catFont);
        textoValor.setAlignment(Element.ALIGN_RIGHT);
        preface.add(textoValor);

        addEmptyLine(preface, 1);
        Paragraph valorFinal = new Paragraph(df.format(valorTransferencia).replace(".", ","), catFont);
        valorFinal.setAlignment(Element.ALIGN_RIGHT);
        preface.add(valorFinal);


        addEmptyLine(preface, 6);
        // Will create: Report generated by: _name, _date
        Paragraph textoFinal = new Paragraph("Este relatório foi gerado pelo Frente de Caixa em:" + new Date(), smallestBold);
        textoFinal.setAlignment(Element.ALIGN_CENTER);
        preface.add(textoFinal);

        document.add(preface);
        document.newPage();

    }

    private void createTable(Paragraph subCatPart)
            throws BadElementException {
        int[] relativeWidths = {100, 70, 70, 70, 70, 70};
        ControladorTransacoes controladorTransacoes = new ControladorTransacoes();
        ArrayList<Transacoes> transacoesDaLista = controladorTransacoes.buscaTransacoesPorIDDaCompra(compraEscolhida.getId());

        PdfPTable table = new PdfPTable(6);
        try {
            table.setWidths(relativeWidths);

        } catch (DocumentException ex) {
            Logger.getLogger(ClienteListaPDF.class.getName()).log(Level.SEVERE, null, ex);
        }

        // t.setBorderColor(BaseColor.GRAY);
        // t.setPadding(4);
        // t.setSpacing(4);
        // t.setBorderWidth(1);

        Phrase frase = new Phrase("Produto", smallBold);
        PdfPCell c1 = new PdfPCell(frase);
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        frase = new Phrase("Código", smallBold);
        c1 = new PdfPCell(frase);
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        frase = new Phrase("Quantidade", smallBold);
        c1 = new PdfPCell(frase);
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        frase = new Phrase("Preço (unid)", smallBold);
        c1 = new PdfPCell(frase);
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        frase = new Phrase("Valor", smallBold);
        c1 = new PdfPCell(frase);
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        frase = new Phrase("Desconto", smallBold);
        c1 = new PdfPCell(frase);
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        table.setHeaderRows(1);

        for (int i = 0; i < transacoesDaLista.size(); i++) {

            Transacoes transacaoDaVez = transacoesDaLista.get(i);
            Phrase fraseTabela = new Phrase(transacaoDaVez.getNomeDoProduto().toUpperCase(), smallNormal);
            table.addCell(fraseTabela);

            fraseTabela = new Phrase(transacaoDaVez.getCodigoDoProduto().toUpperCase(), smallNormal);
            table.addCell(fraseTabela);

            fraseTabela = new Phrase(String.valueOf(transacaoDaVez.getQuantidadeVendidade()), smallNormal);
            table.addCell(fraseTabela);

            fraseTabela = new Phrase(String.valueOf(transacaoDaVez.getPrecoPorUnidade()), smallNormal);
            table.addCell(fraseTabela);

            fraseTabela = new Phrase(String.valueOf(transacaoDaVez.getPrecoPorUnidade() * transacaoDaVez.getQuantidadeVendidade()), smallNormal);
            table.addCell(fraseTabela);

            fraseTabela = new Phrase(String.valueOf(transacaoDaVez.getDescontoDado()), smallNormal);
            table.addCell(fraseTabela);

        }
        subCatPart.add(table);

    }

    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }
}
